
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include "../imagepipe.h"

// select channel function:
// returns the value specified by channel (which can be "r, g, b, a, -r, -g, -b, -a or a number)
Rgb chooseColor( const Image &img )
{
	int r, g, b;
	int size = img.width()*img.height();
	const Rgb *c = img.data();
	
	r = g = b = 0;
	for( int i = 0; i < size; i ++ ) {
		r += RED( c[i] );
		g += GREEN( c[i] );
		b += BLUE( c[i] );
	}
	r /= size;
	g /= size;
	b /= size;
	
	Rgb average = RGB( r, g, b );
	return average;
	
	unsigned int difference = -1;
	Rgb nearest;
	for( int i = 0; i < size; i ++ ) {
		unsigned int newDiff = pixelDiff( average, c[i] );
		if( newDiff < difference ) {
			newDiff = difference;
			nearest = c[i];
		}
	}
	return nearest;
}


extern "C"
{


void applyFilter( const Image &img, Image &dst, const Rect &r2 )
{
	int size = 4;

	//Image colors( new Rgb[ size*size ], size, size );
	Rgb imgdata[ size*size ];
	Image colors( imgdata, size, size );

	// when r is not aligned to a size*size grid,
	// I'll filter the grid that includes the upper-left corner
	// but excludes the lower-right one
	Rect r( r2 );

	if( r.x % size ) { // not aligned at left: going lefter alignin to the grid
		r.x -= r.x % size;
	}
	if( r.w % size ) { // not aligned at right: going lefter alignin to the grid
		r.w -= r.w % size;
	}

	if( r.y % size ) { // not aligned at top: going upper alignin to the grid
		r.y -= r.y % size;
	}
	if( r.h % size ) { // not aligned at bottom: going upper alignin to the grid
		r.h -= r.h % size;
	}

	// processing ...
	for( int x = r.x; x < r.w; x += size ) {
		for( int y = r.y; y < r.h; y += size ) {
			for( int i = 0; i < size; i ++ ) {
				for( int j = 0; j < size; j ++ ) {
					colors.pixel( i, j ) = img.pixel( x+i, y+j );
				}
			}
			Rgb c = chooseColor( colors );
			for( int i = 0; i < size; i ++ ) {
				for( int j = 0; j < size; j ++ ) {
					dst.pixel( x+i, y+j ) = c;
				}
			}
		}
	}

	//delete[] colors.data();
	
}


}
